document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const recordBtn = document.querySelector('.record-btn');
    const stopBtn = document.querySelector('.stop-btn');
    const playBtn = document.querySelector('.play-btn');
    const searchBtn = document.querySelector('.search-btn');
    const audioPlayer = document.querySelector('#audio-preview');
    const audioUpload = document.querySelector('#audio-file');
    const visualizer = document.querySelector('#visualizer');
    const recognitionResult = document.querySelector('.recognition-result');
    const transcriptText = document.querySelector('.transcript-text');
    
    let mediaRecorder;
    let audioChunks = [];
    let audioBlob;
    let isRecording = false;
    let audioContext;
    let analyser;
    let visualizerContext = visualizer.getContext('2d');

    // 初始化音频可视化
    function initAudioVisualizer() {
        audioContext = new (window.AudioContext || window.webkitAudioContext)();
        analyser = audioContext.createAnalyser();
        analyser.fftSize = 2048;
    }

    // 绘制音频波形
    function drawWaveform() {
        const bufferLength = analyser.frequencyBinCount;
        const dataArray = new Uint8Array(bufferLength);
        const width = visualizer.width;
        const height = visualizer.height;
        
        visualizerContext.clearRect(0, 0, width, height);
        visualizerContext.lineWidth = 2;
        visualizerContext.strokeStyle = '#2c5cff';
        visualizerContext.beginPath();

        analyser.getByteTimeDomainData(dataArray);
        const sliceWidth = width / bufferLength;
        let x = 0;

        for (let i = 0; i < bufferLength; i++) {
            const v = dataArray[i] / 128.0;
            const y = v * height / 2;

            if (i === 0) {
                visualizerContext.moveTo(x, y);
            } else {
                visualizerContext.lineTo(x, y);
            }

            x += sliceWidth;
        }

        visualizerContext.lineTo(width, height / 2);
        visualizerContext.stroke();

        if (isRecording) {
            requestAnimationFrame(drawWaveform);
        }
    }

    // 开始录音
    recordBtn.addEventListener('click', async function() {
        try {
            const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
            
            // 初始化音频可视化
            initAudioVisualizer();
            const source = audioContext.createMediaStreamSource(stream);
            source.connect(analyser);
            
            mediaRecorder = new MediaRecorder(stream);
            isRecording = true;
            audioChunks = [];

            mediaRecorder.ondataavailable = (event) => {
                audioChunks.push(event.data);
            };

            mediaRecorder.onstop = () => {
                audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
                const audioUrl = URL.createObjectURL(audioBlob);
                audioPlayer.src = audioUrl;
                audioPlayer.parentElement.style.display = 'block';
                searchBtn.disabled = false;
            };

            // 开始录音
            mediaRecorder.start();
            
            // 更新按钮状态
            recordBtn.disabled = true;
            stopBtn.disabled = false;
            playBtn.disabled = true;
            searchBtn.disabled = true;
            
            // 开始绘制波形
            drawWaveform();
            
        } catch (error) {
            console.error('录音失败:', error);
            alert('无法访问麦克风，请检查权限设置');
        }
    });

    // 停止录音
    stopBtn.addEventListener('click', function() {
        if (mediaRecorder && mediaRecorder.state === 'recording') {
            mediaRecorder.stop();
            isRecording = false;
            
            // 更新按钮状态
            recordBtn.disabled = false;
            stopBtn.disabled = true;
            playBtn.disabled = false;
            
            // 停止所有音轨
            mediaRecorder.stream.getTracks().forEach(track => track.stop());
        }
    });

    // 播放录音
    playBtn.addEventListener('click', function() {
        if (audioPlayer.paused) {
            audioPlayer.play();
            playBtn.innerHTML = '<i class="fas fa-pause"></i> 暂停';
        } else {
            audioPlayer.pause();
            playBtn.innerHTML = '<i class="fas fa-play"></i> 播放';
        }
    });

    // 音频文件上传处理
    audioUpload.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            audioBlob = file;
            const audioUrl = URL.createObjectURL(file);
            audioPlayer.src = audioUrl;
            audioPlayer.parentElement.style.display = 'block';
            playBtn.disabled = false;
            searchBtn.disabled = false;
        }
    });

    // 语音识别按钮点击事件
    searchBtn.addEventListener('click', async function() {
        try {
            // 显示识别状态
            recognitionResult.style.display = 'block';
            transcriptText.textContent = '正在识别...';
            searchBtn.disabled = true;

            // 创建 OpenAI 客户端
            const client = {
                baseURL: 'https://ai.gitee.com/v1',
                headers: {
                    'Authorization': 'Bearer MBJWASWXHAXXUWNXMJTIRS6M7HEAMPMGUPC3Z8JI',
                    'X-Package': '1910'
                }
            };

            // 准备表单数据
            const formData = new FormData();
            formData.append('model', 'whisper-large-v3-turbo');
            formData.append('file', audioBlob);

            // 调用语音识别API
            const response = await fetch('https://ai.gitee.com/v1/audio/translations', {
                method: 'POST',
                headers: {
                    'Authorization': 'Bearer MBJWASWXHAXXUWNXMJTIRS6M7HEAMPMGUPC3Z8JI',
                    'X-Package': '1910'
                },
                body: formData
            });

            if (!response.ok) {
                const errorData = await response.json().catch(() => ({}));
                throw new Error(`HTTP error! status: ${response.status}, message: ${errorData.error?.message || 'Unknown error'}`);
            }

            const result = await response.json();
            
            if (result.text) {
                const text = result.text;
                
                // 创建识别结果卡片
                const resultCard = document.createElement('div');
                resultCard.className = 'recognition-card';
                resultCard.innerHTML = `
                    <div class="card-header">
                        <i class="fas fa-file-alt"></i>
                        <span>识别结果</span>
                        <div class="card-actions">
                            <button class="edit-btn">
                                <i class="fas fa-edit"></i>
                                编辑
                            </button>
                            <button class="generate-image-btn">
                                <i class="fas fa-image"></i>
                                检索图像
                            </button>
                        </div>
                    </div>
                    <div class="card-content">
                        <textarea class="result-text" disabled>${text}</textarea>
                    </div>
                    <div class="card-footer">
                        <button class="save-btn" style="display: none;">
                            <i class="fas fa-save"></i>
                            保存
                        </button>
                        <button class="cancel-btn" style="display: none;">
                            <i class="fas fa-times"></i>
                            取消
                        </button>
                    </div>
                `;

                // 添加编辑和生成图像功能
                const textarea = resultCard.querySelector('.result-text');
                const editBtn = resultCard.querySelector('.edit-btn');
                const generateImageBtn = resultCard.querySelector('.generate-image-btn');
                const saveBtn = resultCard.querySelector('.save-btn');
                const cancelBtn = resultCard.querySelector('.cancel-btn');
                let originalText = text;

                editBtn.addEventListener('click', () => {
                    textarea.disabled = false;
                    textarea.focus();
                    editBtn.style.display = 'none';
                    saveBtn.style.display = 'inline-flex';
                    cancelBtn.style.display = 'inline-flex';
                });

                saveBtn.addEventListener('click', () => {
                    textarea.disabled = true;
                    originalText = textarea.value;
                    editBtn.style.display = 'inline-flex';
                    saveBtn.style.display = 'none';
                    cancelBtn.style.display = 'none';
                });

                cancelBtn.addEventListener('click', () => {
                    textarea.value = originalText;
                    textarea.disabled = true;
                    editBtn.style.display = 'inline-flex';
                    saveBtn.style.display = 'none';
                    cancelBtn.style.display = 'none';
                });

                // 添加生成图像功能
                generateImageBtn.addEventListener('click', async function() {
                    try {
                        generateImageBtn.disabled = true;
                        generateImageBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 生成中...';
                        
                        const response = await fetch('https://ai.gitee.com/v1/images/generations', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                                'Authorization': 'Bearer MBJWASWXHAXXUWNXMJTIRS6M7HEAMPMGUPC3Z8JI',
                                'X-Package': '1910'
                            },
                            body: JSON.stringify({
                                model: "HunyuanDiT-v1.2-Diffusers-Distilled",
                                size: "1024x1024",
                                guidance_scale: 6,
                                num_inference_steps: 35,
                                prompt: textarea.value
                            })
                        });

                        if (!response.ok) {
                            throw new Error(`HTTP error! status: ${response.status}`);
                        }

                        const data = await response.json();
                        
                        if (data && data.data && Array.isArray(data.data) && data.data.length > 0) {
                            // 创建图像结果区域
                            const imageResult = document.createElement('div');
                            imageResult.className = 'generated-image-result';
                            imageResult.innerHTML = `
                                <h4>检索的图像</h4>
                                <div class="generated-image">
                                    <img src="" alt="检索的图像">
                                    <button class="download-btn">
                                        <i class="fas fa-download"></i>
                                        下载图像
                                    </button>
                                </div>
                            `;
                            
                            const img = imageResult.querySelector('img');
                            const downloadBtn = imageResult.querySelector('.download-btn');
                            
                            // 设置图片源
                            if (typeof data.data[0] === 'string' && data.data[0].startsWith('data:image')) {
                                img.src = data.data[0];
                            } else if (data.data[0].b64_json) {
                                img.src = `data:image/png;base64,${data.data[0].b64_json}`;
                            } else if (data.data[0].url) {
                                img.src = data.data[0].url;
                            }
                            
                            // 添加下载功能
                            downloadBtn.onclick = () => downloadImage(img.src);
                            
                            // 将图像结果添加到卡片中
                            resultCard.appendChild(imageResult);
                        }
                    } catch (error) {
                        console.error('图像检索失败:', error);
                        alert('图像检索失败，请稍后重试\n错误信息：' + error.message);
                    } finally {
                        generateImageBtn.disabled = false;
                        generateImageBtn.innerHTML = '<i class="fas fa-image"></i> 检索图像';
                    }
                });

                // 将卡片添加到识别结果区域
                const cardContainer = document.querySelector('.recognition-cards') || document.createElement('div');
                cardContainer.className = 'recognition-cards';
                cardContainer.insertBefore(resultCard, cardContainer.firstChild);
                if (!recognitionResult.contains(cardContainer)) {
                    recognitionResult.appendChild(cardContainer);
                }

                transcriptText.textContent = text;
            } else {
                throw new Error('识别结果为空');
            }

        } catch (error) {
            console.error('语音识别失败:', error);
            transcriptText.textContent = '识别失败: ' + error.message;
            alert('语音识别失败，请稍后重试\n' + error.message);
        } finally {
            searchBtn.disabled = false;
        }
    });

    // 确保音频格式正确
    function ensureWavFormat(blob) {
        return new Promise((resolve, reject) => {
            // 如果已经是 WAV 格式，直接返回
            if (blob.type === 'audio/wav') {
                resolve(blob);
                return;
            }

            // 转换为 WAV 格式
            const audioContext = new (window.AudioContext || window.webkitAudioContext)();
            const fileReader = new FileReader();

            fileReader.onload = async function() {
                try {
                    const arrayBuffer = this.result;
                    const audioBuffer = await audioContext.decodeAudioData(arrayBuffer);
                    
                    // 创建离线上下文
                    const offlineContext = new OfflineAudioContext(
                        audioBuffer.numberOfChannels,
                        audioBuffer.length,
                        audioBuffer.sampleRate
                    );

                    // 创建音频源
                    const source = offlineContext.createBufferSource();
                    source.buffer = audioBuffer;
                    source.connect(offlineContext.destination);
                    source.start();

                    // 渲染音频
                    const renderedBuffer = await offlineContext.startRendering();
                    
                    // 转换为 WAV blob
                    const wavBlob = await new Promise(resolve => {
                        const length = renderedBuffer.length * 4 + 44;
                        const buffer = new ArrayBuffer(length);
                        const view = new DataView(buffer);
                        const channels = renderedBuffer.numberOfChannels;
                        const sampleRate = renderedBuffer.sampleRate;

                        // WAV 文件头
                        writeString(view, 0, 'RIFF');
                        view.setUint32(4, length - 8, true);
                        writeString(view, 8, 'WAVE');
                        writeString(view, 12, 'fmt ');
                        view.setUint32(16, 16, true);
                        view.setUint16(20, 1, true);
                        view.setUint16(22, channels, true);
                        view.setUint32(24, sampleRate, true);
                        view.setUint32(28, sampleRate * channels * 2, true);
                        view.setUint16(32, channels * 2, true);
                        view.setUint16(34, 16, true);
                        writeString(view, 36, 'data');
                        view.setUint32(40, length - 44, true);

                        // 写入音频数据
                        const data = new Float32Array(renderedBuffer.getChannelData(0));
                        let offset = 44;
                        for (let i = 0; i < data.length; i++) {
                            const sample = Math.max(-1, Math.min(1, data[i]));
                            view.setInt16(offset, sample < 0 ? sample * 0x8000 : sample * 0x7FFF, true);
                            offset += 2;
                        }

                        resolve(new Blob([buffer], { type: 'audio/wav' }));
                    });

                    resolve(wavBlob);
                } catch (error) {
                    reject(error);
                }
            };

            fileReader.onerror = reject;
            fileReader.readAsArrayBuffer(blob);
        });
    }

    // 辅助函数：写入字符串到 DataView
    function writeString(view, offset, string) {
        for (let i = 0; i < string.length; i++) {
            view.setUint8(offset + i, string.charCodeAt(i));
        }
    }

    // 设置画布大小
    function resizeCanvas() {
        visualizer.width = visualizer.offsetWidth;
        visualizer.height = visualizer.offsetHeight;
    }

    // 初始化时设置画布大小
    resizeCanvas();
    // 窗口大小改变时重新设置画布大小
    window.addEventListener('resize', resizeCanvas);

    // 在文件末尾添加下载图像函数
    async function downloadImage(url) {
        try {
            let imageBlob;
            
            if (url.startsWith('data:')) {
                // 如果是base64数据
                const base64Data = url.split(',')[1];
                const binaryString = window.atob(base64Data);
                const bytes = new Uint8Array(binaryString.length);
                for (let i = 0; i < binaryString.length; i++) {
                    bytes[i] = binaryString.charCodeAt(i);
                }
                imageBlob = new Blob([bytes], { type: 'image/png' });
            } else {
                // 如果是URL
                const response = await fetch(url);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                imageBlob = await response.blob();
            }

            // 创建下载链接
            const downloadUrl = window.URL.createObjectURL(imageBlob);
            const a = document.createElement('a');
            a.href = downloadUrl;
            a.download = `generated-image-${Date.now()}.png`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(downloadUrl);
        } catch (error) {
            console.error('下载失败:', error);
            alert('图像下载失败，请稍后重试\n错误信息：' + error.message);
        }
    }
}); 